package com.example.dma.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
public class jwtUtil {
    private static long time=1000*60*60*24;
    private static String signature="dengJiaMing";
    public static String creatAccessToken(String name,String email){
        JwtBuilder jwtBuilder= Jwts.builder();
        String jwtToken=jwtBuilder
                .setHeaderParam("type","JWT")
                .setHeaderParam("alg","HS256")
                .claim("name",name)
                .claim("email",email)
                .setSubject("test")
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return jwtToken;
    }


    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(signature)
                .parseClaimsJws(token)
                .getBody();

        // 可添加额外的校验逻辑
        if (claims.getExpiration().before(new Date())) {
            throw new RuntimeException("Token has expired");
        }

        return claims.get("name", String.class);
    }
}
